package reversi.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XmlParser {

	public XmlParser(){
		
	}
	
	public Document string2DOM(String s) {

		Document tmpX = null;
		DocumentBuilder builder = null;

		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (javax.xml.parsers.ParserConfigurationException error) {
			
			String msgerror = "Error crando factory String2DOM "
					+ error.getMessage();
			return null;
		}
		try {

			tmpX = (Document) builder.parse(new ByteArrayInputStream(s
					.getBytes()));

		} catch (org.xml.sax.SAXException error) {
			
			String msgerror = "Error parseo SAX String2DOM "
					+ error.getMessage();
			return null;
		} catch (IOException error) {
			
			String msgerror = "Error generando Bytes String2DOM "
					+ error.getMessage();
			return null;
		}
		return tmpX;
	}
	
	public String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if (nl != null && nl.getLength() > 0) {
			Element el = (Element) nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}
	
	public String crearXml(String a, String b){
		String xml="<registro>" +
					"<dato>"+ a +"</dato>" +
					"<dato>"+ b +"</dato>" +
					"</registro>";
		return xml;
	}
	public String crearXml(String a, String b, String c){
		String xml="<registro>" +
					"<dato>"+ a +"</dato>" +
					"<dato>"+ b +"</dato>" +
					"<dato>"+ c +"</dato>" +
					"</registro>";
		return xml;
	}
	public String crearXml(String a, String b, String c, String d){
		String xml="<registro>" +
					"<dato>"+ a +"</dato>" +
					"<dato>"+ b +"</dato>" +
					"<dato>"+ c +"</dato>" +
					"<dato>"+ d +"</dato>" +
					"</registro>";
		return xml;
	}
	public ArrayList<String> getDatos(Document doc){

		Element docEle=doc.getDocumentElement();
		NodeList nl = docEle.getElementsByTagName("dato");
		ArrayList<String> texto = new ArrayList<String>(10);
		if (nl != null && nl.getLength() > 0) {
			for (int i = 0; i < nl.getLength(); i++) {

				Element el = (Element) nl.item(i);
				String dato = el.getFirstChild().getNodeValue();

				texto.add(dato);

			}
		}
		return texto;
		
	}
	
	
}
